package shudu;

import java.util.Arrays;

public class Sudoku {
    public int[][] data;

    public static void main(String[] args) {
        Sudoku sudoku = new Sudoku();
        int[][] dsdf = {{8, 0, 0, 0, 0, 0, 0, 0, 0},
                {0, 0, 3, 6, 0, 0, 0, 0, 0},
                {0, 7, 0, 0, 9, 0, 2, 0, 0},
                {0, 5, 0, 0, 0, 7, 0, 0, 0},
                {0, 0, 0, 0, 4, 5, 7, 0, 0},
                {0, 0, 0, 1, 0, 0, 0, 3, 0},
                {0, 0, 1, 0, 0, 0, 0, 6, 8},
                {0, 0, 8, 5, 0, 0, 0, 1, 0},
                {0, 9, 0, 0, 0, 0, 4, 0, 0}};
        sudoku.data = dsdf;
        sudoku.calculate();
    }

    public void calculate() {
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                if (data[i][j] == 0) {
                    if (!randomNumber(i, j)){
                        return;
                    }
                }
            }
        }
    }

    public boolean randomNumber(int i, int j) {
        for (int k = 1; k <= 9; k++) {
            data[i][j] = k;
            if (checkAll(i,j)){
                if (i == 8 && j == 8){
                    this.print(data);
                }else{
                    calculate();
                }
            }else {
                data[i][j] = 0;
            }
        }
        return false;
    }


    public boolean checkAll(int i, int j) {
        return checkRow(i, j) && checkColumn(i, j) && checkBox(i, j);
    }

    public boolean checkRow(int i, int j) {
        for (int k = 0; k < 9; k++) {
            if (j != k && data[i][k] == data[i][j]) {
                return false;
            }
        }
        return true;
    }

    public boolean checkColumn(int i, int j) {
        for (int k = 0; k < 9; k++) {
            if (i != k && data[k][j] == data[i][j]) {
                return false;
            }
        }
        return true;
    }

    public boolean checkBox(int i, int j) {
        //获取大的box在哪个区域
        int m = i / 3;
        int n = j / 3;
        //循环小区域
        for (int p = 0; p < 3; p++) {
            for (int q = 0; q < 3; q++) {
                int x = m * 3 + p;
                int y = n * 3 + q;
                if (x != i && y != j && data[x][y] == data[i][j]) {
                    return false;
                }
            }
        }
        return true;
    }

    public void print(int[][] data) {
        for (int[] datum : data) {
            System.out.println(Arrays.toString(datum));
        }
        System.out.println("================================");
    }
}
